package com.cc.filter;

import org.springframework.stereotype.Component;

import javax.servlet.Filter;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * @program:
 * @ClassName:
 * @description:
 * @author: zgc
 * @date:
 * @Version 1.0
 **/
@Component
public class CrossOriginFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        // 设置允许跨域的域名或模式
        response.setHeader("Access-Control-Allow-Origin", "*");
        // 是否支持发送cookie
        response.setHeader("Access-Control-Allow-Credentials", "true");
        // 放行的请求方式
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS");
        // 预检请求的有效期
        response.setHeader("Access-Control-Max-Age", "3600");
        // 放行的那些原始头的信息
        response.setHeader("Access-Control-Allow-Headers", "*");
        // 暴露的响应头信息
        response.setHeader("Access-Control-Expose-Headers", "*");
        // 如果是预检请求(OPTIONS)，则直接返回，不继续处理
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return ;
        }
        // 放行
        filterChain.doFilter(request, response);
    }

}
